from django.shortcuts import render, redirect, reverse
from django.http import HttpResponse
from django.views import View
from django.contrib.auth import authenticate, logout, login
from .form import UserLoginForm, UserRegisterModelForm
from django.contrib.auth.decorators import login_required

from myblogs.utils.emails import test1
from myaccount.models import User
from myblogs.utils import get_valid_img
import json
import os
import base64
from django.shortcuts import get_object_or_404

# auth中用户权限有关的类。auth可以设置每个用户的权限。
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt

next_path = '/'
def MyLogin(request):


    if request.method == 'GET':
        form = UserLoginForm()

        path = request.get_full_path()
        global  next_path
        next_path = path.split('next=')[-1]
        print("next_path:", next_path)


        if request.session.get('is_login', None):  # 不允许重复登录
            return redirect(next_path)

        return render(request, "account/login.html", {"form": form})
    else:
        username = request.POST.get("username")
        password = request.POST.get("password")
        validcode = request.POST.get("validcode")
        keep_str = request.session['keep_str']
        form = UserLoginForm(request.POST)
        flag = False

        if form.is_valid():
            user = authenticate(request, username=username, password=password)
            print("cleaned_data:", form.cleaned_data)
            if user:
                login(request, user)
                flag = True
        if flag:
            print(LoginView.path)
            return redirect(next_path)
        else:
            return HttpResponse("账号或密码输入有误，请重新输入")



class LoginView(View):
    """
    用户登录
    """
    next_path = '/'


    def get(self, request):
        self.path = request.path
        form = UserLoginForm()
        path = request.get_full_path()
        global  next_path
        next_path = path.split('=')[-1]
        print("next_path:", next_path)

        if request.session.get('is_login', None):  # 不允许重复登录
            return redirect('/index/')

        return render(request, "account/login.html", {"form": form})

    def post(self, request):
        username = request.POST.get("username")
        password = request.POST.get("password")
        validcode = request.POST.get("validcode")
        form = UserLoginForm(request.POST)

        flag = False
        if form.is_valid():
            user = authenticate(request,username=username, password=password)
            print("cleaned_data:",form.cleaned_data)
            if user:
                login(request, user)
                flag = True
        if flag:
            return redirect(LoginView.next_path)
        else:
            return HttpResponse("账号或密码输入有误，请重新输入")


class RegisterView(View):
    def get(self, request):
        current_path = request.path
        form = UserRegisterModelForm()
        return render(request, 'account/register.html', {"form": form})

    def post(self, request):
        form = UserRegisterModelForm()
        if form.is_valid():
            data = form.cleaned_data
            print("data:", data)
            user = form.save(commit=False)
            user.set_password(data['password'])
            user.save()
            test1(request)
            return HttpResponse('ok')
        else:
            errors = form.errors
            print("errors:", errors)
            return render(request, 'account/register.html', {"form": form})


class UserLogoutView(View):
    """
    用户退出
    """

    def get(self, request):
        path = request.path
        logout(request)
        return redirect(reverse('index'))


class ResetPwdView(View):
    def post(self,request):
        reset_username = request.POST.get('username')
        reset_password = request.POST.get('password')


class UserDeleteView(View):
    def post(self, request):
        print(request.POST)

        return HttpResponse("删除成功")



@login_required
# 个人信息
def profile(request):
    user = request.user
    return render(request,'account/profile.html',{"user":user})

@login_required
@csrf_exempt #取消当前函数防跨站请求伪造功能，即便settings中设置了全局中间件。
def profile_udpate(request):
    if request.is_ajax():
        key = request.POST.get('key')  # request.POST.get('')不存在默认为空，request.POST[]不存在报错
        username = request.POST['username']
        user_profile = get_object_or_404(User, username=username)

        if key == 'link':
            link = request.POST['link']
            User.objects.filter(username=username).update(link=link)
            link = User.objects.filter(username=username).first().link
            linkJson = {'link': link}
            return HttpResponse(json.dumps(linkJson))

        elif key == 'avatar':
            upload_image = request.FILES.get('avatar')
            image_name = user_profile.save_avatar(upload_image)
            user_profile.avatar = os.path.join('avatar', user_profile.username, image_name)
            print("user avatar path:",user_profile.avatar)
            user_profile.save()
            url = user_profile.avatar.url
            dataJson = {'url': url}
            return HttpResponse(json.dumps(dataJson))

